<?php

namespace PKApp\Content\Classes;

use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;
use PKFrame\DataHandler\Pages;

class ContentTemplateTag extends ContentListController
{

    private $_entity_category, $_list_order;
    private $_is_makeHtml;

    public function __construct()
    {
        $this->_is_makeHtml = request()->controller() == 'AdminMakeHtml';
    }

    public function category($params): array
    {
        $parentId = Numbers::To(Arrays::GetKey('parentId', $params));
        $assign = Arrays::GetKey('assign', $params);
        !empty($assign) ?: $assign = 'categoryList';
        $id_site = Numbers::To(Arrays::GetKey('siteId', $params));
        $id_site > 0 ?: $id_site = $this->getSiteEntity()->Id;
        $list_category = $this->getListCategory([
            'siteId' => $id_site,
            'parentId' => $parentId,
            'isShow' => 1,
        ]);
        if (!Arrays::Is($list_category)) {
            return [$assign => []];
        }
        $count_list = count($list_category);
        $line_num = Arrays::GetKey('num', $params);
        if (!empty($line_num)) {
            // 是否要翻页
            $is_pages = Arrays::GetKey('isPage', $params);
            if (empty($is_pages)) {
                $line_start = 0;
                $line_end = $line_num < $count_list ? $line_num : $count_list;
            } else {
                $this->getPages();
                $line_start = (self::$pageIndex - 1) * $line_num;
                $line_end = $line_start + $line_num;
            }
        } else {
            $line_start = 0;
            $line_end = $count_list;
        }
        // 遍历返回栏目的列表
        $list_result = [];
        for ($i = $line_start; $i < $line_end; $i++) {
            $item_entity = $list_category[$i];
            $item_entity['seo'] = Arrays::Unserialize($item_entity['seo']);
            $template = Arrays::Unserialize($item_entity['template']);
            unset($item_entity['template'], $item_entity['power']);
            $item_entity['url'] = self::UrlPathOfCategory($item_entity, $template, $this->getSitePath());
            $item_entity['seo']['description'] = htmlspecialchars_decode($item_entity['seo']['description']);
            $list_result[] = $item_entity;
        }
        return [$assign => $list_result];
    }

    private function _getCategoryByNow($catId)
    {
        $this->_entity_category = Arrays::GetKey($catId, $this->list_category, 'Category_Empty', 'content');
        $this->_entity_category['template'] = Arrays::Unserialize($this->_entity_category['template']);
        $this->is_filterContentMirror = toBool('isFilterContentMirror', $this->_entity_category['template']);
        // 排序
        $order = Arrays::GetKey(
            Numbers::To($this->_entity_category['template']['orderList']),
            dict('category_content_orderList', 'content')
        );
        if (Arrays::Is($order)) {
            (is_array($this->_list_order) && count($this->_list_order) > 0)
                ?: $this->_list_order = $order;
        } else {
            $this->noticeByJson('category_order_empty', 'content');
        }
    }

    public function lists($params_tpl): array
    {
        $params_view = $this->getListCategoryByParentId($params_tpl);
        if ($attribute = Arrays::GetKey('attribute', $params_tpl)) {
            if (array_key_exists($attribute, dict('content_attribute', 'content'))) {
                if (in_array($attribute, ['toHead', 'toPush'])) {
                    $params_view[$attribute] = true;
                    $this->_list_order = ['field' => 'listSort', 'mode' => 'ASC'];
                } else {
                    $this->_list_order = ['field' => 'toTop', 'mode' => 'DESC'];
                }
            } else {
                $this->noticeByPage('Content_attribute_Error', null, 'content');
            }
        } elseif ($attribute_not = Arrays::GetKey('notAttribute', $params_tpl)) {
            if (array_key_exists($attribute_not, dict('content_attribute', 'content'))) {
                if (in_array($attribute_not, ['toHead', 'toPush'])) {
                    $params_view[$attribute_not] = 0;
                }
            } else {
                $this->noticeByPage('Content_attribute_Error', null, 'content');
            }
        }
        return $this->_getContentListByNotPageNav($params_view, $params_tpl);
    }

    public function related($params_tpl): array
    {
        $controller = strtolower(request()->controller());
        $is_page_content = (strtolower(request()->module()) == 'content')
            && in_array($controller, ['category', 'content']);
        $is_page_content || $this->_is_makeHtml ?: $this->noticeByPage('TemplateTag_RelatedError');
        if ($controller == 'category') {
            array_key_exists('catId', $params_tpl) ?: $this->noticeByPage('Category_idEmpty');
        } else {
            array_key_exists('catId', $params_tpl) ?: $params_tpl['catId'] = request()->get('catId');
        }
        $params_view = $this->getListCategoryByParentId($params_tpl);
        if (array_key_exists('keywords', $params_tpl) && !empty($params_tpl['keywords'])) {
            $keywords = str_replace('，', ',', $params_tpl['keywords']);
            if (stristr($keywords, ',')) {
                $keywords = explode(',', $keywords);
            }
            if (isset($keywords) && is_array($keywords)) {
                foreach ($keywords as $index => $item) {
                    $keywords[$index] = urldecode($item);
                }
                $params_view['query_like'] = array_unique(array_filter($keywords));
            } else {
                $params_view['query_like'] = urldecode($keywords);
            }
        }
        if (request()->has('contentId', 'get')) {
            $params_view[] = ['id', '!=', Numbers::To(request()->get('contentId'))];
        }
        return $this->_getContentListByNotPageNav($params_view, $params_tpl);
    }

    private function _getContentListByNotPageNav($params_view, $params_tpl): array
    {
        if ((bool)$this->is_list_category) {
            $order = Arrays::GetKey(0, dict('category_content_orderList', 'content'));
            Arrays::Is($this->_list_order) ?: $this->_list_order = $order['value'];
        } else {
            $this->_getCategoryByNow($params_tpl['catId']);
        }
        $this->list_lineNum = Numbers::To(Arrays::GetKey('num', $params_tpl));
        $this->list_lineNum > 0 ?: $this->noticeByPage('TemplateTag_listNumber_zero');
        $assign = (array_key_exists('assign', $params_tpl) && !empty($params_tpl['assign'])) ? $params_tpl['assign'] : 'contentList';
        $list_result = $this->getContentList($params_view, $this->_list_order);
        if (Arrays::Is($list_result) && array_key_exists('filterWord', $params_tpl) && !empty($params_tpl['filterWord'])) {
            $list_filterWord = '/' . str_replace(',', '|', $params_tpl['filterWord']) . '/';
            $list_filter = [];
            foreach ($list_result as $index => $item) {
                preg_match_all($list_filterWord,$item['title'],$matches);
                $matches = end($matches);
                Arrays::Is($matches) ?: $list_filter[] = $item;
            }
            $list_result = $list_filter;
        }
        return [
            $assign => $list_result,
        ];
    }

    public function categoryContentList(): array
    {
        $is_page_category = (strtolower(request()->module()) == 'content') && (strtolower(request()->controller()) == 'category');
        $is_page_category || $this->_is_makeHtml ?: $this->noticeByPage('TemplateTag_ContentListError');
        $params_view = $this->getListCategoryByParentId(request()->get());
        $this->_getCategoryByNow(request()->get('catId'));
        $this->GetPages();
        $this->list_lineNum = Numbers::To($this->_entity_category['template']['listDataSize']);
        $this->list_lineNum > 0 ?: $this->noticeByPage('Category_listNumber_zero');
        $tpl_config = $this->_entity_category['template'];
        return [
            'contentListData' => $this->getContentList($params_view, $this->_list_order),
            'pageNavList' => Pages::PageNavs($this->count_content, $this->list_lineNum, self::$pageIndex,
                self::UrlPathOfCategory($this->_entity_category, $tpl_config, $this->getSitePath(), true),
                toBool('isClosePageByFirst', $tpl_config)
            ),
        ];
    }

    public function Main()
    {
    }
}
